package akka.shoppingcart.application

import akka.Done
import akka.javasdk.eventsourcedentity.EventSourcedEntity
import akka.shoppingcart.domain.LineItem
import akka.shoppingcart.domain.ShoppingCart
import akka.shoppingcart.domain.ShoppingCartEvent
import cn.hutool.log.Log

class ShoppingCartEntity : EventSourcedEntity<ShoppingCart, ShoppingCartEvent>() {
  private val log by lazy { Log.get(javaClass) }

  override fun applyEvent(event: ShoppingCartEvent): ShoppingCart =
      when (event) {
        is ShoppingCartEvent.ItemAdded -> currentState().onItemAdded(event)
      }

  fun addItem(item: LineItem): Effect<Done> {
    if (currentState().checkedOut) {
      log.info("Cart id=${currentState().cartId} is already checked out.")
      return effects().error("Cart is already checked out.")
    }
    if (item.quantity <= 0) {
      log.info("Quantity for item {} must be greater than zero.", item.productId)
      return effects().error("Quantity for item " + item.productId + " must be greater than zero.")
    }
    return effects().persist(ShoppingCartEvent.ItemAdded(item)).thenReply { Done.getInstance() }
  }
}
